package com.tisson.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.tisson.database.FormatUtil;
import com.tisson.database.StatementUtil;
import com.tisson.pojo.AcDepartment;
import com.tisson.pojo.AdminArea;
import com.tisson.pojo.Function;

public class FunctionDAO {
	private String query;
	private ResultSet rs;
	private Statement stmt;

	public Function findById(String id) throws SQLException {
		stmt = StatementUtil.getStatement();
		query = "select * from function where id = '" + id + "'";
		rs = stmt.executeQuery(query);
		Function function = new Function();
		while (rs.next()) {
			function.setId(FormatUtil.ConvertUuid(rs.getBytes("id")));
			function.setName((String) rs.getObject("name"));
			function.setUrl((String) rs.getObject("url"));
			function.setNode(rs.getInt("node"));
		}
		rs.close();
		stmt.close();
		return function;
	}

	public List findAll() throws SQLException {
		stmt = StatementUtil.getStatement();
		query = "select * from function";
		rs = stmt.executeQuery(query);
		List list = new ArrayList();
		while (rs.next()) {
			Function function = new Function();
			function.setId(FormatUtil.ConvertUuid(rs.getBytes("id")));
			function.setName((String) rs.getObject("name"));
			function.setUrl((String) rs.getObject("url"));
			function.setNode(rs.getInt("node"));
			list.add(function);
		}
		rs.close();
		stmt.close();
		return list;
	}

	public void save(Function function) throws SQLException {
		stmt = StatementUtil.getStatement();
		query = "insert into function (name, url , node)values('" + function.getName()
				+ "','" + function.getUrl() + "', " +function.getNode()+ ")";
		stmt.executeUpdate(query);
		stmt.close();
	}

	public void update(Function function) throws SQLException {
		stmt = StatementUtil.getStatement();
		query = "update function set " + "name = '" + function.getName()
				+ "',url = '" + function.getUrl() + "',node = " +function.getNode()+ " where id = '"
				+ function.getId() + "'";
		stmt.executeUpdate(query);
		stmt.close();
	}

	public void delete(Function function) throws SQLException {
		stmt = StatementUtil.getStatement();
		query = "delete from function where id = '" + function.getId() + "'";
		stmt.executeUpdate(query);
		stmt.close();
	}
}
